package org.itboys.shop.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;

import com.google.common.collect.Maps;
import org.apache.ibatis.annotations.Param;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.CommonConstants.StaticParam;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.tools.ImagePathUtils;
import org.itboys.commons.utils.tools.ResponseManager;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.member.service.MemberService;
import org.itboys.portal.constant.PortalConstants.codes;
import org.itboys.portal.dto.PortalInfoCommentDTO;
import org.itboys.portal.dto.PortalInfoDTO;
import org.itboys.portal.dto.mobile.MobiInfoCommentResult;
import org.itboys.portal.dto.mobile.MobiPortalInfoResult;
import org.itboys.portal.dto.wx.InfoIndexDto;
import org.itboys.portal.entity.PortalInfo;
import org.itboys.portal.entity.PortalInfoComment;
import org.itboys.portal.entity.PortalItem;
import org.itboys.portal.service.PortalInfoCommentService;
import org.itboys.portal.service.PortalInfoService;
import org.itboys.portal.service.PortalItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;

/**
 * 资讯
 */
@RestController
@RequestMapping("/wx/portal")
public class WXPortalController extends BaseController{
	@Autowired
	private PortalItemService itemService;
	@Autowired
	private PortalInfoService infoService;
	@Autowired
	private PortalInfoCommentService commentService;
	@Autowired
	private MemberService memberService;

	@RequestMapping("/index")
	public void index(@RequestParam Integer type,
							  @RequestParam Integer pageNo,
							  HttpServletRequest request,
							  HttpServletResponse response,Model model) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		try {
			//要组装的最终结果
			InfoIndexDto dto1=new InfoIndexDto();
			InfoIndexDto dto2=new InfoIndexDto();
			InfoIndexDto dto3=new InfoIndexDto();
			switch (type) {
				case 1://新闻
					dto1.setCarousel(transfer(codes.Government_carousel,3));
					dto1.setArea_1(transfer(codes.Government_area_1,2));
					dto1.setArea_2(transfer(codes.Government_area_2,2));
					dto1.setArea_3(rTransfer(codes.Government_area_3,pageNo));
					ResponseManager.normalResult(dto1,response,null);
				break;
				case 2://景区
					dto2.setCarousel(transfer(codes.Center_carousel,3));
					dto2.setArea_1(transfer(codes.Center_area_1,2));
					dto2.setArea_2(transfer(codes.Center_area_2,2));
					dto2.setArea_3(rTransfer(codes.Center_area_3,pageNo));
					ResponseManager.normalResult(dto2,response,null);
				break;
				case 3://商家
					dto3.setCarousel(transfer(codes.Shop_carousel,3));
					dto3.setArea_1(transfer(codes.Shop_area_1,2));
					dto3.setArea_2(transfer(codes.Shop_area_2,2));
					dto3.setArea_3(rTransfer(codes.Shop_area_3,pageNo));
					model.addAttribute("dto3",dto3);
					ResponseManager.normalResult(dto3,response,null);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			logger.error("/mobile/core/portal/info/itemList error",e);
			ResponseManager.SystemError(response, null);
		}
	}

	@RequestMapping("/listRefresh")
	public void listRefresh(@RequestParam Integer type,
									@Param("pageNo")  Integer pageNo,
									HttpServletRequest request,
									HttpServletResponse response,Model model) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		try {
			switch (type) {
				case 1://新闻
					ResponseManager.normalResult(rTransfer(codes.Government_area_3,pageNo),response,null);
					break;
				case 2://景区
					ResponseManager.normalResult(rTransfer(codes.Center_area_3,pageNo),response,null);
					break;
				case 3://商家
					ResponseManager.normalResult(rTransfer(codes.Shop_area_3,pageNo),response,null);
					break;
				default:
					break;
			}

		} catch (Exception e) {
			logger.error("/mobile/core/portal/info/itemList error",e);
			ResponseManager.SystemError(response, null);
		}

	}
	@RequestMapping("/detail")
	public void findInfo(@RequestParam Long id,
						 HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		try {
		PortalInfoDTO info = infoService.findById(id);
		AjaxUtils.renderJson(response, info);
		} catch (Exception e) {
			logger.error("/mobile/core/portal/info/itemList error",e);
			ResponseManager.SystemError(response, null);
		}
	}
	//新增评论
	@RequestMapping("/insert")
	public void addComment(@ModelAttribute PortalInfoComment portalInfoComment,HttpServletRequest request, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Member member1 = (Member)request.getSession().getAttribute("user");
		try {
			if(member1.getId() == 0) {
				AjaxUtils.renderText(response, CommonConstants.FAIL);
				return;
			} else {
				Member member = memberService.getById(member1.getId());
				PortalInfoComment comment = new PortalInfoComment();
				if(member != null) {
					comment.setNickName(member.getNickname());
					comment.setLogo(member.getLogo());
				}
				SimpleDateFormat df=new SimpleDateFormat(CommonConstants.DATE.FORMAT_DEFAULT);
				comment.setInfoId(portalInfoComment.getInfoId());
				comment.setMemberId(member1.getId());
				comment.setNickName(portalInfoComment.getNickName());
				comment.setLogo(portalInfoComment.getLogo());
				comment.setContent(portalInfoComment.getContent());
				comment.setTime(df.format(new Date()));
				commentService.save(comment);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	@RequestMapping("/comment")
	public void comment(@RequestParam Long id, HttpServletResponse response,Model model){
		response.setHeader("Access-Control-Allow-Origin", "*");
		try{
			Map<String, Object>param=Maps.newHashMap();
			param.put("infoId",id);
			param.put("orderByKey", "-id");
			List<PortalInfoComment> comments =  commentService.list(param);
			List<PortalInfoCommentDTO> commentResults = Lists.newArrayList();
			SimpleDateFormat df=new SimpleDateFormat(CommonConstants.DATE.FORMAT_DEFAULT);
			for (PortalInfoComment comment : comments){
				PortalInfoCommentDTO dto = new PortalInfoCommentDTO(comment.getMemberId(), comment.getNickName(), comment.getContent(), comment.getTime(),comment.getInfoId(),comment.getLogo());
				commentResults.add(dto);
			}

			AjaxUtils.renderJson(response, commentResults);
		} catch (Exception e) {
			logger.error(" ",e);
			ResponseManager.SystemError(response, null);
		}
	}




	/**
	 * 参数1：codes
	 * 返回值：根据code得到结果集--用于丢到相应栏目
	 */
	public List<MobiPortalInfoResult> transfer(String code,int size){
		PortalItem item=itemService.findByCode(code);//传递code
		List<PortalInfo> carousels=infoService.findInfosByItemId(item.getId(),size);//根据id查询到结果集
		List<MobiPortalInfoResult> carouselResults = Lists.newArrayList();//定义一个泛型集合，接收上个id查询到的结果集
		//遍历之前id查询到的结果集
		forTransfer(carousels,carouselResults);
		//返回之前定义的泛型集合
		return carouselResults;
	}

	public List<MobiPortalInfoResult> rTransfer(String code,int pageNo){
		PortalItem item=itemService.findByCode(code);//传递code
		Map<String, Object>param=Maps.newHashMap();
		param.put("pageNo", pageNo);
		param.put("pageSize",5);
		param.put("itemId",item.getId());
		List<PortalInfo>portalInfos=infoService.listWithPaging(param);
		List<MobiPortalInfoResult> carouselResults = Lists.newArrayList();//定义一个泛型集合，接收上个id查询到的结果集
		//遍历之前id查询到的结果集
		forTransfer(portalInfos,carouselResults);
		//返回之前定义的泛型集合
		return carouselResults;
	}
	public void forTransfer(List<PortalInfo>portalInfos,List<MobiPortalInfoResult> carouselResults){
        SimpleDateFormat df=new SimpleDateFormat(CommonConstants.DATE.FORMAT_DEFAULT);
		for (PortalInfo info:portalInfos){
			MobiPortalInfoResult cr = new MobiPortalInfoResult();//定义一个对象
			cr.setId(info.getId());
			cr.setImage(ImagePathUtils.add(StaticParam.imagePath, info.getImage()));
			cr.setTitle(info.getTitle());
			cr.setTime(df.format(info.getCreateTime()));
			//利用结果集得到的数据存到泛型集合中
			carouselResults.add(cr);
		}
	}
}
